//
//  ChatBaseTableViewCell.m
//  供销宝
//
//  Created by 金晶 on 17/2/14.
//  Copyright © 2017年 金晶. All rights reserved.
//

#import "ChatBaseTableViewCell.h"
#import "ChatTableViewTextCell.h"
#import "ChatTableViewImageCell.h"
#import "ChatTableViewVoiceCell.h"
//#import "WebSocketManage.h"

@interface ChatBaseTableViewCell ()<UIAlertViewDelegate>

@property (nonatomic,strong) UILongPressGestureRecognizer *longPressGesture;

//如果是语音。要点击播放，如果是图片，可能要点击放大
@property (nonatomic,strong) UITapGestureRecognizer * singleTap;
//如果是语音。要点击播放，如果是图片，可能要点击放大
@property (nonatomic,strong) UITapGestureRecognizer * doubleTap;

@property (nonatomic,strong) UITapGestureRecognizer *userInfoTap;

@property (nonatomic,strong) UITapGestureRecognizer *friendInfoTap;



@end

@implementation ChatBaseTableViewCell

+ (UITableViewCell *)cellWithTableView:(ChatTableView *)tableView messageModel:(ChatMessage *)model {

    CGFloat masTop = model.splitTime.length > 0?37:10;
    
    if(model.messageBodyType==ChatMsgBodyType_Text) {
        ChatTableViewTextCell *cell = (ChatTableViewTextCell *)[ChatTableViewTextCell cellWithTableView:tableView messageModel:model withmasTop:masTop];
        
        return cell;
        
    }else if (model.messageBodyType==ChatMsgBodyType_Voice) {
        
        ChatTableViewVoiceCell *cell = (ChatTableViewVoiceCell *)[ChatTableViewVoiceCell cellWithTableView:tableView messageModel:model withmasTop:masTop];
        
        return cell;
        
    }else if(model.messageBodyType==ChatMsgBodyType_Image){
        ChatTableViewImageCell *cell = (ChatTableViewImageCell *)[ChatTableViewImageCell cellWithTableView:tableView messageModel:model withmasTop:masTop];
        
        return cell;
    }else{
        
        ChatBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"baseCell"];
        if (!cell) {
            cell = [[ChatBaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"baseCell"];
        }
        
        return cell;
    }
    
    return nil;
}

+ (CGFloat)cellHeightWithModel:(ChatMessage *)model {
    
    CGFloat masTop = model.splitTime.length > 0?37:10;

    if (model.messageBodyType==ChatMsgBodyType_Text) {
        
        CGFloat maxWith=kScreenWidth-LEFT_WITH-RIGHT_WITH-14-12-4;

        UIFont *textFont=[UIFont systemFontOfSize:16];
        
        NSDictionary *attributes = @{NSFontAttributeName: textFont};

        CGRect rect = [[[Common manager] replaceEmoji:model.msgContent] boundingRectWithSize:CGSizeMake(maxWith, MAXFLOAT)
                                 options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                              attributes:attributes context:nil];
        
        return rect.size.height+26+masTop+20;

    }else if (model.messageBodyType==ChatMsgBodyType_Voice) {
        
        return 40+masTop+20;
        
    }else if (model.messageBodyType==ChatMsgBodyType_Image) {
        
        CGFloat height= [ChatBaseTableViewCell conversionFormat:model];
        
        return 40+height+20;
    }
    
    return 0;
}

+ (CGFloat)conversionFormat:(ChatMessage *)model {
    
    if(model.msgSourceType==CHAT_MSG_SEND) {
        NSString* realSavePath=LocalImagePath(model.toFriendid,model.contentPath);
        return [Common imageShowSize:[[UIImage alloc]initWithContentsOfFile:realSavePath]].height;
        
    }else {
        return model.imageHeight;
    }
}


- (void)loadUserPic:(NSString *)friendStr ChatMdl:(ChatMessage *)chatMdl {
    
    if(chatMdl.msgSourceType ==CHAT_MSG_SEND) {
        
        NSURL *url = [NSURL URLWithString:[[[UserManager shareInstance] user] headPortraitUrl]];
        [self.logoImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"photo"]];
    }else {
        
        NSURL *url = [NSURL URLWithString:chatMdl.toFriendLogo];
        [self.logoImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"photo"]];
    }
}


#pragma 长按事件
- (void)longPressBubbleView:(UILongPressGestureRecognizer *)sender {
    
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self showMenuControllerInView:self bgView:sender.view];
    }
}

//如果是语音。要点击播放，如果是图片，可能要点击放大.可以重写此方法。不必要判断是哪种类型
- (void)handleSingleTap:(UITapGestureRecognizer *)sender {


}

- (void)handleDoubleTap:(UITapGestureRecognizer *)sender {

}

- (void)showMenuControllerInView:(UITableViewCell *)inView
                          bgView:(UIView *)supView {
    
}

- (void)handleUserInfoTap{
    

}

- (void)retryButtonClick:(UIButton *)sender {
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"重发该消处?" delegate:self cancelButtonTitle:@"消取" otherButtonTitles:@"重发", nil];
    
    [alert show];
}

#pragma mark -
#pragma mark -UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if(buttonIndex==1) {
        
//        [[WebSocketManage webSocketManage] sendMessageSentStatusSending:self.chatMdl];
    }
}

#pragma mark - getter
- (UILongPressGestureRecognizer *)longPressGesture {
    
    if(!_longPressGesture){
        
        _longPressGesture=[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressBubbleView:)];
    }
    
    return _longPressGesture;
}

- (UITapGestureRecognizer *)singleTap {
    if(!_singleTap){
        
        _singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];
    }
    return _singleTap;
}

- (UITapGestureRecognizer *)doubleTap {
    if(!_doubleTap){
        
        _doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTap:)];
        [_doubleTap setNumberOfTapsRequired:2];
        [self.singleTap requireGestureRecognizerToFail:_doubleTap];
    }
    return _singleTap;
}

- (UITapGestureRecognizer *)userInfoTap {
    
    if(!_userInfoTap) {
        _userInfoTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleUserInfoTap)];
        
    }
    return _userInfoTap;
}

- (UIImageView *)contextBack {
    
    if(!_contextBack) {
        
        _contextBack=[[UIImageView alloc] init];
        _contextBack.userInteractionEnabled=YES;
#warning 暂时屏蔽长按事件
//        [_contextBack addGestureRecognizer:self.longPressGesture];
        [_contextBack addGestureRecognizer:self.singleTap];
        [_contextBack addGestureRecognizer:self.doubleTap];
        [self.contentView addSubview:_contextBack];
    }
    return _contextBack;
}

- (UIImageView *)coversImageView {
    
    if(!_coversImageView){
        
        _coversImageView=[[UIImageView alloc] init];
        _coversImageView.userInteractionEnabled=YES;
    }
    return _coversImageView;
}

- (UIImageView *)logoImage {
    
    if(!_logoImage){
        
        _logoImage=[[UIImageView alloc] init];
        
        _logoImage.userInteractionEnabled = YES;
        [self.contentView addSubview:_logoImage];
        [_logoImage addGestureRecognizer:self.userInfoTap];
    }
    return _logoImage;
}

- (UIImageView *)imageViewMask {
    
    if(!_imageViewMask){
        
        _imageViewMask = [[UIImageView alloc]init];
    }
    return _imageViewMask;
}

- (UIImageView *)voiceAnimationImageView {
    
    if(!_voiceAnimationImageView){
        
        _voiceAnimationImageView=[[UIImageView alloc] init];
        _voiceAnimationImageView.animationRepeatCount = 0;
        _voiceAnimationImageView.animationDuration = 2;
        [self.contextBack addSubview:_voiceAnimationImageView];
    }
    return _voiceAnimationImageView;
}

- (UILabel *)textMessageLabel {
    
    if(!_textMessageLabel){
        
        _textMessageLabel=[[UILabel alloc] init];
        _textMessageLabel.numberOfLines=0;
        _textMessageLabel.lineBreakMode=NSLineBreakByWordWrapping;
        _textMessageLabel.textColor=[UIColor grayColor];
        [self.contentView addSubview:_textMessageLabel];
        
    }
    return _textMessageLabel;
}

- (UIButton *)retryButton {
    
    if(!_retryButton) {
        
        _retryButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_retryButton setImage:[UIImage imageNamed:@"wechat_resendbut5"] forState:UIControlStateNormal];
        
        [_retryButton addTarget:self action:@selector(retryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.contentView addSubview:_retryButton];
    }
    return _retryButton;
}



- (UILabel *)timeLabel {
    
    if(!_timeLabel){
        
        _timeLabel = [[UILabel alloc]init];
        _timeLabel.font=[UIFont systemFontOfSize:10];
        _timeLabel.backgroundColor= kProgrameBackgroundColor;
        _timeLabel.textColor=[UIColor blackColor];
        _timeLabel.textAlignment=NSTextAlignmentCenter;
        //不想作离屏渲染，对性能不好
        //        _timeLabel.layer.masksToBounds=YES;
        //        _timeLabel.layer.cornerRadius=4;
        //        _timeLabel.layer.borderColor=kProgrameBackgroundColor.CGColor;
        //        _timeLabel.layer.borderWidth=1;
        [self.contentView addSubview:_timeLabel];
        
        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.contentView.mas_top).offset(10);
            make.centerX.equalTo(self.contentView);
            make.width.mas_equalTo(80);
            make.height.mas_equalTo(17);
        }];
    }
    return _timeLabel;
}

- (UILabel *)nickNameLabel{
    if (!_nickNameLabel) {
        _nickNameLabel = [[UILabel alloc] init];
        
        _nickNameLabel.font = [UIFont systemFontOfSize:10.f];
        _nickNameLabel.textColor = [UIColor blackColor];
        //_nickNameLabel.backgroundColor = [UIColor blueColor];
        [self.contentView addSubview:_nickNameLabel];
        
    }
    return _nickNameLabel;
}

- (UILabel *)notificationLabel{
    if (!_notificationLabel) {
        _notificationLabel = [[UILabel alloc] init];
        _notificationLabel.font = [UIFont systemFontOfSize:10.f];
        _notificationLabel.backgroundColor=kProgrameBackgroundColor;
        _notificationLabel.textColor=[UIColor blackColor];
        _notificationLabel.textAlignment=NSTextAlignmentCenter;
        [self.contentView addSubview:_notificationLabel];
        
        _notificationLabel.numberOfLines = 0;//
        WeakSelf(ws);
        //        [_notificationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        //
        //            make.top.equalTo(weakSelf.timeLabel.mas_bottom).offset(10.f);
        //            // 垂直居中
        //            make.centerX.equalTo(weakSelf.contentView);
        //            // 右边不超出
        //            make.right.lessThanOrEqualTo(weakSelf.contentView).offset(-30.f);
        //            // 左边大于等于父View宽度的1/3，注意不是width属性
        //            make.left.greaterThanOrEqualTo(weakSelf.contentView).offset(30.f);
        //        }];
    }
    
    return _notificationLabel;
}

- (UIActivityIndicatorView *)acview {
    
    if(!_acview){
        
        _acview=[[UIActivityIndicatorView alloc] init];
        [_acview setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [self.contentView addSubview:_acview];
    }
    return _acview;
}

- (CGFloat)returnNameTop:(BOOL)isShow {
    
    if(isShow) {
        return 15;
    }else {
        return 0;
    }
}

- (CGRect) getContentWidth:(CGFloat)maxWith withcontent:(NSString *)str {
    
    CGRect rect;
    
    UIFont *textFont = [UIFont systemFontOfSize:16];
    
    NSDictionary *attributes = @{NSFontAttributeName:textFont};
    
    rect = [str boundingRectWithSize:CGSizeMake(maxWith, MAXFLOAT)
                             options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                          attributes:attributes context:nil];
    
    return rect;
}


@end
